﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using IncomeOutcome.Resources;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using Microsoft.Phone;
using IncomeOutcome.Model;
using System.IO;
using System.IO.IsolatedStorage;

namespace IncomeOutcome
{
    public partial class MainPage : PhoneApplicationPage
    {
        #region Members ------------------------------------------------------------------------
        CameraCaptureTask m_CameraCaptureTask;
        WriteableBitmap s_WriteableBitmap;
        public int ItemIndex
        {
            get { return App.S_ViewModel.ItemIndex; }
            //set { App.S_ViewModel.ItemIndex = value; }
        }

        #endregion Members ------------------------------------------------------------------------

        #region Methods ----------------------------------------------------------------
        void ResetControlValue()
        {
            Uri uri = new Uri("/Images/numbutton_bg.jpg", UriKind.Relative);
            ImageAvatar.Source = new BitmapImage(uri);
        }
        #endregion Methods End ----------------------------------------------------------------

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            //ButtonAvatar.Click += ButtonAvatar_Click;
            ImageAvatar.Tap += ImageAvatar_Tap;
          
            m_CameraCaptureTask = new CameraCaptureTask();
            m_CameraCaptureTask.Completed += m_CameraCaptureTask_Completed;

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();

            this.DataContext = App.S_ViewModel;

            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = 
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = ItemIndex > 0;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = 
            ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IsEnabled = ItemIndex < App.S_ViewModel.ItemCount - 1;

            LoadImageAvatar(App.S_ViewModel.ImagePath);
        }

        void ImageAvatar_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            m_CameraCaptureTask.Show();
        }

        void m_CameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null)
            {
                s_WriteableBitmap = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
                ImageAvatar.Source = s_WriteableBitmap;

                App.S_ViewModel.ImagePath = App.S_ViewModel.ItemId + ".jpg";
                e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
                byte[] oImageData = ReadImageBytes(e.ChosenPhoto);
                WriteImageFile(App.S_ViewModel.ImagePath, oImageData);
                App.S_ViewModel.SaveImagePath();
            }
        }
        void WriteImageFile(string pFileName, byte[] pImageData)
        {
            using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var writer = new BinaryWriter(new IsolatedStorageFileStream(pFileName, System.IO.FileMode.Create, isf)))
                {
                    writer.Write(pImageData);
                }
            }
        }
        byte[] ReadImageBytes(Stream pStreamImage)
        {
            byte[] oImageData;
            using (var reader = new BinaryReader(pStreamImage))
            {
                oImageData = reader.ReadBytes((int)pStreamImage.Length);
            }
            return oImageData;
        }
        byte[] ReadImageFile(string pFileName)
        {
            byte[] oImageData;
            using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(pFileName, System.IO.FileMode.Open, isf);
                using (var reader = new BinaryReader(isfs))
                {
                    oImageData = reader.ReadBytes((int)isfs.Length);
                    //reader.Read(oImageData, 0, (int)isfs.Length);
                }
            }
            return oImageData;
        }
        string ToString(WriteableBitmap pWriteableBitmap)
        {
                byte[] byteArray = null;
                using (MemoryStream stream = new MemoryStream())
                {
                    s_WriteableBitmap.SaveJpeg(stream, s_WriteableBitmap.PixelWidth, s_WriteableBitmap.PixelHeight, 0, 100);
                    stream.Seek(0, SeekOrigin.Begin);
                    //byteArray = stream.ToArray();
                    byteArray = stream.GetBuffer();
                }
                return Convert.ToBase64String(byteArray);
        }
        WriteableBitmap ToWriteableBitmap(string pImageBase64String)
        {
            byte[] data = Convert.FromBase64String(pImageBase64String);
            Stream memStream = new MemoryStream(data);
            return PictureDecoder.DecodeJpeg(memStream);
        }
        void LoadImageAvatar(string pFileName)
        {
            if (string.IsNullOrWhiteSpace(pFileName))
            {
                Uri uri = new Uri("/Images/numbutton_bg.jpg", UriKind.Relative);
                ImageAvatar.Source = new BitmapImage(uri);
            }
            else
            {
                byte[] oImageData = ReadImageFile(pFileName);
                Stream memStream = new MemoryStream(oImageData);
                s_WriteableBitmap = PictureDecoder.DecodeJpeg(memStream);
                ImageAvatar.Source = s_WriteableBitmap;
            }
        }
        void ButtonAvatar_Click(object sender, RoutedEventArgs e)
        {
            m_CameraCaptureTask.Show();
        }

        ////Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        // Number click.
        private void ButtonNumber_Click(object sender, RoutedEventArgs e)
        {
            string sNum = (sender as Button).Content.ToString();
            string sInput = TxtInput.Text;
            int iIndex = sInput.IndexOf('.');
            if ((iIndex < 0 && sInput.Length < 6) || sNum == "." || (sInput.Length - iIndex < 3))
            {
                if (sInput == "0")
                {
                    if (sNum == ".")
                        sInput += sNum;
                    else if (!sNum.Contains('0'))
                        sInput = sNum;
                }
                else
                {
                    if (sNum == "00" && (sInput.Length == 5 || sInput.Length - iIndex == 2))
                        sInput += "0";
                    else
                        sInput += sNum;
                }
                //if (sInput == "0" && !("00.").Contains(sNum))
                //    sInput = sNum;
                //else if (!sNum.Contains('0') || iIndex > 0)
                //        sInput += sNum;
            }
            TxtInput.Text = sInput;
            ButtonDot.IsEnabled = sInput.IndexOf('.') < 0;
        }
        // Sign click.
        private void ButtonSign_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            if ("+" == btn.Content.ToString())
                btn.Content = "-";
            else
                btn.Content = "+";
        }

        private void ButtonReset_Click(object sender, RoutedEventArgs e)
        {
            App.S_ViewModel.ResetItemValues();
            this.Focus();
        }

        private void ButtonCancel_Click(object sender, RoutedEventArgs e)
        {
            TxtInput.Text = "0";
            ButtonDot.IsEnabled = true;
        }

        private void ButtonBack_Click(object sender, RoutedEventArgs e)
        {
            // If only one number character.
            if (TxtInput.Text.Length == 1)
            {
                TxtInput.Text = "0";
            }
            else
            {
                string sInput = TxtInput.Text;
                int len = sInput.Length - 1;
                if (sInput[len] == '.')
                    ButtonDot.IsEnabled = true;
                TxtInput.Text = sInput.Substring(0, len);
            }
        }

        private void ButtonEnter_Click(object sender, RoutedEventArgs e)
        {
            if (TxtInput.Text != "0")
            {
                App.S_ViewModel.AddItemValue();
                ButtonDot.IsEnabled = true;
            }
        }

        private void ButtonAddItem_Click(object sender, EventArgs e)
        {
            if (App.S_ViewModel.AddItem("ItemName"))
            {
                //if (ItemIndex < App.S_ViewModel.ItemCount - 1)
                //    ItemIndex++;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = 
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = ItemIndex > 0;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = 
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IsEnabled = ItemIndex < App.S_ViewModel.ItemCount - 1;

                LoadImageAvatar(App.S_ViewModel.ImagePath);
            }
        }

        private void ButtonDeleteItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this item?", "Warning", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                if (App.S_ViewModel.RemoveItem())
                {
                    //if (ItemIndex > 0 && ItemIndex == App.S_ViewModel.ItemCount)
                    //    ItemIndex--;
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled =
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = ItemIndex > 0;
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled =
                    ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IsEnabled = ItemIndex < App.S_ViewModel.ItemCount - 1;

                    LoadImageAvatar(App.S_ViewModel.ImagePath);
                }
            }
        }

        private void ButtonFirstItem_Click(object sender, EventArgs e)
        {
            if (App.S_ViewModel.FirstItem())
            {
                //ItemIndex = 0;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled =
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = 
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IsEnabled = true;
                    
                LoadImageAvatar(App.S_ViewModel.ImagePath);
            }
        }

        private void ButtonPreviousItem_Click(object sender, EventArgs e)
        {
            if (App.S_ViewModel.PreviousItem())
            {
                //if (ItemIndex > 0)
                //    ItemIndex--;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = 
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = ItemIndex > 0;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = 
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IsEnabled = true;

                LoadImageAvatar(App.S_ViewModel.ImagePath);
            }
        }

        private void ButtonNextItem_Click(object sender, EventArgs e)
        {
            if (App.S_ViewModel.NextItem())
            {
                //if (ItemIndex < App.S_ViewModel.ItemCount - 1)
                //    ItemIndex++;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = 
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled =
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IsEnabled = ItemIndex < App.S_ViewModel.ItemCount - 1;
                    
                LoadImageAvatar(App.S_ViewModel.ImagePath);
            }
        }

        private void ButtonLastItem_Click(object sender, EventArgs e)
        {
            if (App.S_ViewModel.LastItem())
            {
                //ItemIndex = App.S_ViewModel.ItemCount - 1;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = 
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled =
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IsEnabled = false;

                LoadImageAvatar(App.S_ViewModel.ImagePath);
            }
        }
    }
}